import { defineComponent, reactive, toRefs, provide, getCurrentInstance, onMounted, computed, onUnmounted, watch, watchEffect, onBeforeUnmount } from 'vue';

import appDialog from '@/components/dialog/appDialog.vue';
import xpTime from '@/components/toolPanel/xpTime.vue';
import xpWeather from '@/components/toolPanel/xpWeather.vue';
import xpCalendar from '@/components/toolPanel/xpCalendar.vue';
import xpNote from '@/components/toolPanel/xpNote.vue';
import xpTodo from '@/components/toolPanel/xpTodo.vue';
import slotWindow from '@/components/window/slotWindow.vue';
import iframeWindow from '@/components/window/iframeWindow.vue';
import xpCalendars from '@/components/xpCalendars/index.vue';
import appMenu from '@/components/dialog/appMenu.vue';
import appFolder from '@/components/dialog/appFolder.vue';
import appBack from '@/components/drawer/appBack.vue';
import island from '@/components/island/index.vue';
import slotComponents from '@/components/window/slot';
import addApp from '@/components/dialog/addApp.vue';
import islandOption from '@/components/dialog/islandOption.vue';

import { useUsersStore } from '@/store/user';
import { useAppStore } from '@/store/app';

import useWindow from '@/hooks/useWindow';
import useCheck from '@/hooks/useCheck';

import { defaultApp } from '@/config';

import { ElMessageBox } from 'element-plus';
import { InfoFilled } from '@element-plus/icons-vue';

export default defineComponent({
    name:'toolPanel',
    props: {

    },
    components: {
        island,
        xpTime,
        xpWeather,
        xpCalendar,
        xpNote,
        xpTodo,
        slotWindow,
        iframeWindow,
        xpCalendars,
        appDialog,
        appMenu,
        appFolder,
        appBack,
        ...slotComponents,

        addApp,
        islandOption
    },
    emits:[],
    setup (props, context) 
    {
        const { proxy }:any = getCurrentInstance();
        const userStore = useUsersStore();
        const appStore = useAppStore();
        const useWindowHooks = useWindow();
        let data = reactive({
            loading:true,

            backupLoading:false,
            backupInfo:'',
            appData:[] as any,
            stateImg:require('@/assets/error.png'),
            stateText:'加载失败',
            stateVisible:false,
            visible:false,

            left:0,
            top:0,
            menuVisible:false,
            appMenuVisible:false,
            contextAppData:null as any,

            folderData:null as any,
            folderVisible:false,

            addAppVisible:false,

            timer:null as any,
            timer1:null as any,

            islandOptionVisible:false
        });

        let methods = {
            // 验证用户身份
            async checkUser ()
            {
                console.log('开始验证用户身份');
                try
                {
                    await userStore.checkUserState();
                    // 同步远程数据
                    await methods.getData();
                    data.loading = false;
                }
                catch (err:any)
                {
                    console.error('验证异常 ——' + err.message);
                    userStore.loginOut();
                }
            },
            // 同步数据
            async getData ()
            {
                data.loading = true;
                try
                {
                    await appStore.getMyBackupData();
                }
                catch (err)
                {
                    console.error(err);
                    data.stateVisible = true;
                }
                data.loading = false;
            },
            reloadData ()
            {
                proxy.$utils.cache.backupId.remove();
                methods.getData();
            },
            closeAppDialog ()
            {
                data.visible = false;
                methods.closeMenu();
            },
            closeMenu ()
            {
                data.appMenuVisible = false;
                data.menuVisible = false;
            },
            handleMenu (e, value, item = null)
            {
                methods.closeMenu();
                setTimeout(() => 
                {
                    data[value] = true;
                    data.left = e.pageX;
                    data.top = e.pageY;
                    data.contextAppData = item;
                }, 100);
            },
            openFolder (item)
            {
                data.folderVisible = true;
                data.folderData = item;
            },
            createFolder ()
            {
                ElMessageBox.prompt('文件夹名称', '新建文件夹', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    inputErrorMessage: '请输入正确的文件夹名称',
                    inputPlaceholder:'请输入文件夹名称',
                    inputValue:'',
                    customClass:'z-message-box',
                    inputValidator:(value) => 
                    {
                        if (value.length > 8 || value.length < 1)
                        {
                            return '名称长度须在 1 - 8 位';
                        }
                        return true;
                    },
                    beforeClose: async (action, instance, done) => 
                    {
                        if (action === 'confirm') 
                        {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '提交中...';
                            appStore.createFolder(instance.inputValue);
                            done();
                        } 
                        else 
                        {
                            done();
                        }
                    }
                })
                    .then(({ value }) => 
                    {
                        console.log(value);
                    });
            },
            async backupAllData ()
            {
                data.backupLoading = true;
                data.backupInfo = '正在备份';
                try
                {
                    await appStore.backupAllData();
                    data.backupInfo = '备份完成';
                }
                catch (err)
                {
                    data.backupInfo = '备份失败';
                }
                setTimeout(() => 
                {
                    data.backupLoading = false;
                }, 2000);
            }
        };

        onMounted(() => 
        {
            methods.checkUser();
        });

        onUnmounted(() => 
        {
            //
        });

        watch(() => appStore.noteData, (newValue, oldValue) => 
        {
            data.timer && clearTimeout(data.timer);
            if (newValue && oldValue)
            {
                data.timer = setTimeout(() => 
                {
                    console.log('开始备份数据');
                    appStore.backupNoteData();
                }, 3000);
            }
        }, {deep:true});

        watch(() => appStore.todoData, (newValue, oldValue) => 
        {
            data.timer1 && clearTimeout(data.timer1);
            
            if (newValue && oldValue)
            {
                data.timer1 = setTimeout(() => 
                {
                    console.log('开始备份数据');
                    appStore.backupTodoData();
                }, 3000);
            }
        }, {deep:true});

        watchEffect(() => 
        {
            if (data.menuVisible || data.appMenuVisible)
            {
                document.addEventListener('click', methods.closeMenu);
            }
            else 
            {
                document.removeEventListener('click', methods.closeMenu);
            }
        });

        onBeforeUnmount(() => 
        {
            data.timer1 && clearTimeout(data.timer1);
            data.timer && clearTimeout(data.timer);
        });
        
        return {
            ...toRefs(data),
            ...methods,
            ...useCheck(),
            ...toRefs(useWindowHooks.data),
            ...useWindowHooks.methods,
            appStore,
            userStore,
            defaultApp,
            InfoFilled
        };
    }
});